﻿using iMES.Core.Extensions;
using iMES.Core.ManageUser;
using iMES.Core.Utilities;
using iMES.Custom.IRepositories;
using iMES.Entity.DomainModels;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using YUN.Ware.IRepositroies;
using ClosedXML.Excel;

namespace YUN.Ware.Services
{
    public partial class Ware_WaresServices
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IWare_WaresRepository _repository;//访问数据库
        private readonly IBase_NumberRuleRepository _numberRuleRepository;//自定义编码规则访问数据库
        [ActivatorUtilitiesConstructor]
        public Ware_WaresServices(IHttpContextAccessor httpContextAccessor,
            IWare_WaresRepository repository,
            IBase_NumberRuleRepository numberRuleRepository) : base(repository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = repository;
            _numberRuleRepository = numberRuleRepository;
        }
        WebResponseContent webResponse = new WebResponseContent();
        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="saveDataModel"></param>
        /// <returns></returns>
        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            //此处saveModel是从前台提交的原生数据，可对数据进修改过滤
            AddOnExecuting = (Ware_Wares tool, object list) =>
            {
                if (string.IsNullOrWhiteSpace(tool.WareCode))
                    tool.WareCode = GetToolCode();
                //如果返回false,后面代码不会再执行
                if (repository.Exists(x => x.WareCode == tool.WareCode))
                {
                    return webResponse.Error("仓库编码已存在");
                }
                return webResponse.OK();
            };
            return base.Add(saveDataModel);
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="saveDataModel"></param>
        /// <returns></returns>
        public override WebResponseContent Update(SaveModel saveDataModel)
        {
            //此处saveModel是从前台提交的原生数据，可对数据进修改过滤
            AddOnExecuting = (Ware_Wares tool, object list) =>
            {
                if (string.IsNullOrWhiteSpace(tool.WareCode))
                    tool.WareCode = GetToolCode();
                //如果返回false,后面代码不会再执行
                if (repository.Exists(x => x.WareCode == tool.WareCode))
                {
                    return webResponse.Error("仓库编码已存在");
                }
                return webResponse.OK();
            };
            return base.Update(saveDataModel);
        }

        /// <summary>
        /// 自动生成设备编号
        /// </summary>
        /// <returns></returns>
        public string GetToolCode()
        {
            //查询当天最新的订单号
            string defectItemCode = repository.FindAsIQueryable(x => x.WareCode.Length > 8)
                .OrderByDescending(x => x.WareCode)
                .Select(s => s.WareCode)
                .FirstOrDefault();
            Base_NumberRule numberRule = _numberRuleRepository.FindAsIQueryable(x => x.FormCode == "Tool")
                .OrderByDescending(x => x.CreateDate)
                .FirstOrDefault();
            if (numberRule != null)
            {
                // 构建基础规则部分：前缀 + 时间格式
                string rule = numberRule.Prefix + DateTime.Now.ToString(numberRule.SubmitTime.Replace("hh", "HH"));

                // 处理序列号部分
                if (string.IsNullOrEmpty(defectItemCode))
                {
                    // 如果没有提供上一个编号，从1开始
                    rule += "1".PadLeft(numberRule.SerialNumber, '0');
                }
                else
                {
                    // 从现有编号中提取最后几位数字并加1
                    string serialPart = defectItemCode.Substring(Math.Max(0, defectItemCode.Length - numberRule.SerialNumber));
                    int nextSerial = serialPart.GetInt() + 1;
                    rule += nextSerial.ToString("0".PadLeft(numberRule.SerialNumber, '0'));
                }

                return rule;
            }
            else //如果自定义序号配置项不存在，则使用日期生成
            {
                return DateTime.Now.ToString("yyyyMMddHHmmssffff");
            }
        }

        /// <summary>
        /// 导出处理
        /// </summary>
        /// <param name="pageData"></param>
        /// <returns></returns>
        //public override WebResponseContent Export(PageDataOptions pageData)
        //{
        //    //限定只能导出当前角色能看到的所有用户
        //    QueryRelativeExpression = (IQueryable<Sys_User> queryable) =>
        //    {
        //        if (UserContext.Current.IsSuperAdmin) return queryable;
        //        // 这里假设获取仓库相关权限角色ID有对应的方法，需根据实际情况调整
        //        List<int> roleIds = SomeService.Instance.GetWareRelatedRoleIds(UserContext.Current.RoleId);
        //        return queryable.Where(x => roleIds.Contains(x.SomeRoleIdProperty) || x.SomeUserIdProperty == UserContext.Current.UserId);
        //    };

        //    base.ExportOnExecuting = (List<Ware_Wares> list, List<string> ignoreColumn) =>
        //    {
        //        if (!ignoreColumn.Contains("Role_Id"))
        //        {
        //            ignoreColumn.Add("Role_Id");
        //        }
        //        if (!ignoreColumn.Contains("RoleName"))
        //        {
        //            ignoreColumn.Remove("RoleName");
        //        }
        //        string path = null;
        //        string fileName = null;
        //        WebResponseContent webResponse = new WebResponseContent(true);

        //        try
        //        {
        //            List<Dictionary<string, object>> listDic = new List<Dictionary<string, object>>();
        //            foreach (var item in list)
        //            {
        //                Dictionary<string, object> dic = new Dictionary<string, object>();
        //                dic.Add("仓库主键", item.WareId);
        //                dic.Add("仓库编号", item.WareCode);
        //                dic.Add("仓库名称", item.WareName);
        //                dic.Add("仓库区域", item.AreaId);
        //                dic.Add("面积", item.WareSqure);
        //                dic.Add("位置编码", item.LocationCode);
        //                dic.Add("负责人", item.Creator);
        //                dic.Add("状态", item.WareState);
        //                dic.Add("备注", item.WareNote);
        //                // 处理仓库平面图字段（假设为照片相关字段）
        //                if (!string.IsNullOrEmpty(item.WareImg))
        //                {
        //                    // 这里简单处理，如果是文件路径，可根据实际情况做更多如校验文件存在等操作
        //                    dic.Add("仓库平面图", item.WareImg);
        //                }
        //                else
        //                {
        //                    dic.Add("仓库平面图", "");
        //                }
        //                listDic.Add(dic);
        //            }
        //            fileName = DateTime.Now.ToString("yyyyMMddHHmmsss") + ".xlsx";
        //            path = EPPlusHelper.ExportGeneralExcel(listDic, fileName);
        //        }
        //        catch (Exception ex)
        //        {
        //            //Logger.Error($"解析表单出错：{fileName}，错误信息{ex.Message}。");
        //            return webResponse.Error("导出仓库信息出错");
        //        }
        //        webResponse.Code = null;
        //        return webResponse.OK(null, path);
        //    };
        //    return base.Export(pageData);
        //}
    }
}
